package com.heima.user.service.impl;

import com.heima.common.exception.CustException;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        // 1. 参数校验
        //    是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //    operation的值 必须是0 或 1
        Short operation = dto.getOperation();
        if (operation.intValue() !=0 && operation.intValue() !=1){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"关注方式错误");
        }
        //   是否已经关注过 ZSCORE
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();

        //   自己不能关注自己
        if(user.getId() == dto.getAuthorApUserId()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"自己不能关注自己");
        }
        // 2. 判断operation的值是否等于 0
        if(operation.intValue() == 0){
            // 参数1: 在集合中找 (key)   参数2: 要找的元素    返回值: 如果有这个元素返回 score  如果没有返回null
            Double score = zSetOperations.score(UserRelationConstants.FOLLOW_LIST + user.getId(), String.valueOf(dto.getAuthorApUserId()));//
            if(score != null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"你已经关注过该作者");
            }
            // 2.1 如果是0  关注该作者  ZADD  集合添加数据
            zSetOperations.add(UserRelationConstants.FOLLOW_LIST + user.getId(),String.valueOf(dto.getAuthorApUserId()),System.currentTimeMillis());
            zSetOperations.add(UserRelationConstants.FANS_LIST + dto.getAuthorApUserId(),String.valueOf(user.getId()),System.currentTimeMillis());
        }else {
            // 2.2 如果是1  取关该作者  ZREM  集合删除数据
            zSetOperations.remove(UserRelationConstants.FOLLOW_LIST + user.getId(),String.valueOf(dto.getAuthorApUserId()));
            zSetOperations.remove(UserRelationConstants.FANS_LIST + dto.getAuthorApUserId(),String.valueOf(user.getId()));
        }
        return ResponseResult.okResult();
    }
}
